require(["./config"], () => {
  require(["template", "fly", "header", "footer"], template => {
    class Detail {
      constructor() {
        this.init().then(() => {
          this.addToCart(); //添加到购物车
          this.saveShopMsg(); //用来存储商品的信息
        });
      }
      init() {
        const id = Number(window.location.search.slice(4));
        //promise   ==>异步==>同步化
        return new Promise(resolve => {
          $.get(
            "http://rap2api.taobao.org/app/mock/245051/detail",
            { id },
            resp => {
              if (resp.code === 200) {
                const { detail } = resp.body;
                this.detail = { ...detail, id };
                $("#box").html(template("detailTemplate", { ...this.detail }));
                $(".big ul li")
                  .last()
                  .addClass("show");
                resolve();
              }
            }
          );
        });
      }
      //存储商品的添加信息
      saveShopMsg() {
        this.$add.on("click", () => {
          //版本ID索引
          const versionIndex = this.index;
          // 获取版本价格
          const versionPrice = this.price[versionIndex];
          //获取数量
          const num = this.num;
          // console.log(versionIndex, versi,onPrice, num);
          // console.log(typeof versionIndex,, typeof versionPrice, typeof num);
          this.detail = { ...this.detail, num, versionIndex, versionPrice };
          // console.log(this.detail)
          // 模拟获取购物车信息
          let cart = window.localStorage.getItem("cart");
          console.log(cart)
          if (cart) {
            //购物车存在
            //将取到转化为对象
            cart = JSON.parse(cart);
            //判断同类商品是否存在
            let shopFlag = true;
            // console.log('-------')
            cart.forEach(item => {
              // console.log(item)
              if (item.id === this.detail.id) {
                if (item.versionIndex === this.detail.versionIndex) {
                  item.num += num;
                  shopFlag = false;
                }
              }
            });
              //如果不是同类商品  增加
              // console.log(shopFlag)
              // console.log(this.detail)
            if (shopFlag) {
              cart.push({
                ...this.detail
              });
            }
            window.localStorage.setItem("cart", JSON.stringify(cart));
          } else {
            //购物车没有数据 存入数据
            window.localStorage.setItem(
              "cart",
              JSON.stringify([
                {
                  ...this.detail
                }
              ])
            );
          }
          // 设置总价的localStorage
          window.localStorage.setItem('allprice',this.allprice)
        });
      }
      // 添加到购物车数据变换关系
      addToCart() {
        this.$ulis = $("ul li"); //大图片
        this.$smallD = $(".small div"); //小图片
        this.$big = $(".big"); //大的div
        this.$mask = $(".mask"); //mask
        this.$fangda = $(".fangda"); //放大的div
        this.$fangdaD = $(".fangda img"); //放大的所有图片
        this.$version = $(".center"); //版本的div
        this.$versions = $(".center li"); //  所有版本
        this.$add = $(".add"); //加入购物车
        this.$top = $(".righttop"); //数量增减
        this.$down = $(".rb"); //数量减少
        this.$price = $(".price"); //价格
        this.price = this.detail.price; //对应索引的价格数组
        this.bx = parseFloat($(".fangda img").css("width")); //放大图片的尺寸
        this.by = parseFloat($(".fangda img").css("height"));
        this.$allP = $(".addbox span");
        this.$allC = $(".allPrice span");
        this.$priceA = $(".allPrice p");
        this.allprice = 0; //设置总价默认0
        this.num = 1; //索引对应的初始数量1
        this.index = 1; //初始索引
        this.$num = $(".numleft"); //显示的数量
        // this.init(); //初始化
        this.flag = false;
        //添加事件
        this.eventTouch(); //小图片点击
        this.mask(); //移入放大图片
        this.versionsClick(); //版本点击
        this.changenum(); //修改数量
        this.addtocar(); //添加到购物车
        this.allPrice(); //查看总价
      }
      // 图片切换  价格切换等
      eventTouch() {
        var that = this;
        this.$smallD.on("click", "img", function() {
          that.index = $(this.parentNode).index();
          that.$add.removeClass("point").addClass("point2");
          //设置可以添加
          that.flag = true;
          // 小图片高亮
          $(this.parentNode)
            .addClass("ac")
            .siblings()
            .removeClass("ac");
          //版本高亮
          $(that.$versions[that.index])
            .addClass("ac")
            .siblings()
            .removeClass("ac");
          //放大图片切换
          $(that.$fangdaD[that.index])
            .addClass("show")
            .siblings()
            .addClass("hide")
            .removeClass("show");
          //价格切换
          that.$price.text(that.price[that.index] * that.num + "元");
          //图片切换
          $(that.$ulis[that.index])
            .addClass("show")
            .siblings()
            .removeClass("show");
        });
      }
      //   进入big后mask的显示和移动，移出消失
      //   放大图片的显示和移动，移出后消失
      mask() {
        const that = this;
        this.$big.mouseover(function() {
          //mask显示
          that.$mask.addClass("show");
          //放大图片
          that.$fangda.addClass("show");
          that.$big.mousemove(function(e) {
            // mask的移动
            let x = e.pageX - $(this).offset().left - 35;
            let y = e.pageY - $(this).offset().top - 37.5;
            if (x < 0) x = 0;
            else if (280 - 70 < x && x < 280) x = 280 - 70;
            if (y < 0) y = 0;
            else if (300 - 75 < y && y < 300) y = 300 - 75;
            that.$mask.css({ left: x, top: y });
            //放大图片移动
            const mulX = (that.bx / 280) * x;
            const mulY = (that.by / 300) * y;
            $(".fangda img").css({ left: -mulX, top: -mulY });
          });
        });
        this.$big.mouseleave(function() {
          that.$mask.removeClass("show");
          that.$fangda.removeClass("show");
        });
      }
      //版本切换
      versionsClick() {
        const that = this;
        this.$version.on("click", "li", function() {
          that.flag = true;
          that.$add.removeClass("point").addClass("point2");
          that.index = $(this).index();
          //点击的版本高亮
          $(this)
            .addClass("ac")
            .siblings()
            .removeClass("ac");
          //小图片高亮
          $(that.$smallD[that.index])
            .addClass("ac")
            .siblings()
            .removeClass("ac");
          //价格切换
          that.$price.text(that.price[that.index] * that.num + "元");
          //大图片切换
          $(that.$ulis[that.index])
            .addClass("show")
            .siblings()
            .removeClass("show");
          //放大图片切换
          $(that.$fangdaD[that.index])
            .addClass("show")
            .siblings()
            .removeClass("show");
        });
      }
      //修改数量
      changenum() {
        const that = this;
        this.$down.on("click", function() {
          if (that.num == 1) {
          } else {
            that.num--;
            if (that.num == 1)
              that.$down.addClass("point").removeClass("point2");
            that.$num.text(that.num);
            that.$price.text(that.price[that.index] * that.num + "元");
          }
        });
        this.$top.on("click", function() {
          if (that.flag) {
            that.$down.addClass("point2").removeClass("point");
            that.num++;
            that.$num.text(that.num);
            that.$price.text(that.price[that.index] * that.num + "元");
          } else {
            alert("请先选择版本");
          }
        });
      }
      //添加到购物车的效果
      addtocar() {
        const that = this;
        this.$add.on("click", function(e) {
          that.allprice = that.allprice + that.price[that.index] * that.num;
          that.$priceA.text((that.allprice.toFixed(2)));
          if (that.flag) {
            $(
              '<div id="fly" style="width:40px;height:40px;border-radius:50%;background:#008c8c;text-align:center;line-height:40px"></div>'
            ).fly({
              start: {
                left: e.clientX, //开始位置（必填）#fly元素会被设置成position: fixed
                top: e.clientY //开始位置（必填）
              },
              end: {
                left:
                  $(".addbox span").offset().left - $(window).scrollLeft() + 25, //结束位置（必填）
                top:
                  $(".addbox span").offset().top - $(window).scrollTop() + 15, //结束位置（必填）
                width: 20, //结束时高度
                height: 20 //结束时高度
              },
              //   autoPlay: false, //是否直接运动,默认true
              speed: 1.1, //越大越快，默认1.2
              vertex_Rtop: 100, //运动轨迹最高点top值，默认20
              onEnd: function() {
                let addnum = $(".addbox span").text() - 0; //获取数量
                $(".addbox span").text(addnum + that.num); //更改增加后的数量
                this.destroy(); //销毁动画块
              } //结束回调
            });
          } else {
            alert("请先选择版本");
          }
          // $('#fly').play(); //autoPlay: false后，手动调用运动
          // $('#fly').destroy(); //移除dom
        });
      }
      // 计算添加商品的总价
      allPrice() {
        let that = this;
        this.$allP.on("click", function() {
          $(".allPrice").slideDown();
        });
        this.$allC.on("click", function() {
          $(".allPrice").slideUp();
        });
      }
    }
    new Detail();
  });
});
